// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
module.exports = class extends think.cmswing.modIndex {
  /**
   * index action
   * @return {Promise} []
   * 封面入口
   */
  indexAction() {
    // console.log(this);
    // auto render template file index_index.html

    return this.body = '封面入口';
    // return this.display();
  }

  /**
   * 列表入口
   * @returns {*}
   */
  async listAction() {
    // if (!this.is_login) return this.redirect('/');
    // 获取栏目信息
    let cate = this.m_cate;
    this.active = ['/' + cate.name + '?mokuaibiaoshi=' + this.get('mokuaibiaoshi')];
    this.assign('mokuaibiaoshi', this.get('mokuaibiaoshi'));
    cate = think.extend({}, cate);
    // 栏目权限验证
    if (!await this.c_verify('visit')) {
      const error = this.controller('cmswing/error');
      return error.noAction('您所在的用户组,禁止访问本栏目！');
    }

    // 获取当前栏目的模型
    const model = this.mod;
    this.assign('model', model);

    // 获取当前分类的所有子栏目
    const subcate = await this.model('cmswing/category').get_sub_category(cate.id);
    subcate.push(cate.id);

    // 当前栏目列表每页行数
    const num = this.page_num();

    // 获取面包屑信息
    await this.breadcrumb();

    // 获取列表数据
    // 条件
    const map = {
      // 'category_id': ['IN', subcate]
      status: 5
    };
    // 排序
    let o = {};
    let selectMap = {};
    let order = this.modget(1) || 0;
    order = Number(order);
    switch (order) {
      case 1:
        o.popular_value = 'DESC';
        break;
      case 2:
        map.is_recommend = 1;
        o.id = 'DESC';
        break;
      case 3:
        map.answer_count = 0;
        o.id = 'DESC';
        break;
      default:
        o.id = 'DESC';
    }
    this.assign('order', order);
    const group_id = 0;
    // 获取分类信息
    const get = this.get('category') || 0;
    const query = get.split('-');
    let sortid = query[3] || 0;
    if (!think.isEmpty(sortid)) {
      // map.sort_id = sortid;
    }
    let sortarr = query[4] ? decodeURIComponent(query[4]) : null;
    let nsobj = {};
    let sort = await this.model('cmswing/category').get_category(cate.id, 'documentsorts');
    if (sort) {
      this.assign('sorturl', get.split('-')[4]);
      sort = JSON.parse(sort);
      if (sortid == 0) {
        sortid = sort.defaultshow;
      }
      const typevar = await this.model('typevar').where({sortid: sortid}).order('displayorder ASC').select();
      for (const val of typevar) {
        val.option = await this.model('typeoption').where({optionid: val.optionid}).find();
        if (val.option.type == 'select' || val.option.type == 'radio') {
          if (val.option.identifier == 'shangpingleibie') {
            const fengleiRes = await this.model('material').field('id,label,pid').select({where: {status: 1}});
            const fenglei = arr_to_tree(fengleiRes, 0, null, true);
            val.rules = fenglei;
            selectMap[val.option.identifier] = fengleiRes.reduce((a, c) => { a[c.id] = c.label; return a }, {});
            val.option.rules = {choices: selectMap[val.option.identifier] };
          } else if (!think.isEmpty(val.option.rules)) {
            val.option.rules = JSON.parse(val.option.rules);
            val.rules = parse_type_attr(val.option.rules.choices);
            selectMap[val.option.identifier] = parse_type_map(val.option.rules.choices);
            val.option.rules.choices = parse_config_attr(val.option.rules.choices);
          }
        } else if (val.option.type == 'checkbox') {
          if (!think.isEmpty(val.option.rules)) {
            val.option.rules = JSON.parse(val.option.rules);
            val.rules = parse_type_attr(val.option.rules.choices);
            selectMap = parse_type_map(val.option.rules.choices);
            for (const v of val.rules) {
              v.id = 'l>' + v.id;
            }
            val.option.rules.choices = parse_config_attr(val.option.rules.choices);
          }
        } else if (val.option.type == 'range') {
          if (!think.isEmpty(val.option.rules)) {
            const searchtxt = JSON.parse(val.option.rules).searchtxt;
            const searcharr = [];
            if (!think.isEmpty(searchtxt)) {
              const arr = searchtxt.split(',');
              const len = arr.length;
              for (var i = 0; i < len; i++) {
                const obj = {};
                if (!think.isEmpty(arr[i - 1])) {
                  if (i == 1) {
                    obj.id = 'd>' + arr[i];
                    obj.name = '低于' + arr[i];
                    obj.pid = 0;
                    searcharr.push(obj);
                  } else {
                    obj.id = arr[i - 1] + '>' + arr[i];
                    obj.name = arr[i - 1] + '-' + arr[i];
                    obj.pid = 0;
                    searcharr.push(obj);
                  }
                }
              }
              searcharr.push({id: 'u>' + arr[len - 1], name: '高于' + arr[len - 1], pid: 0});
            }
            val.option.rules = JSON.parse(val.option.rules);
            val.rules = searcharr;
          }
        }
      }
      this.assign('typevar', typevar);
    }
    if (!think.isEmpty(sortarr)) {
      sortarr = sortarr.split('|');

      nsobj = {};
      const optionidarr = [];
      const valuearr = [];
      for (const v of sortarr) {
        const qarr = v.split('_');
        nsobj[qarr[0]] = qarr[1];
        if (qarr[1] != 0) {
          const vv = qarr[1].split('>');
          if (vv[0] == 'd' && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['<', vv[1]];
          } else if (vv[0] == 'u' && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['>', vv[1]];
          } else if (vv[0] == 'l' && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['like', `%"${vv[1]}"%`];
          } else if (!think.isEmpty(vv[0]) && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['BETWEEN', Number(vv[0]), Number(vv[1])];
          } else {
            if (selectMap[qarr[0]]) {
              let query = '';
              if (qarr[0] == 'xinxileixing') {
                query = qarr[1] == 'x' ? '0' : qarr[1];
              } else {
                const arr = get_id_path(qarr[1]);
                for (const i of arr) {
                  if (selectMap[qarr[0]][i] != '全部') {
                    if (think.isEmpty(query)) {
                      query = selectMap[qarr[0]][i];
                    } else {
                      query += '-' + selectMap[qarr[0]][i];
                    }
                  }
                }
              }
              map[qarr[0]] = ['like', `%${query}%`];
            } else {
              if (qarr[0] == 'diqu') {
                qarr[1] = qarr[1].replace(':', '-');
                this.assign('diqu', qarr[1]);
              }
              map[qarr[0]] = ['like', `%${qarr[1]}%`];
            }
          }
        }
      }
    }
    let diqu = this.get('diqu') || '';
    diqu = decodeURI(diqu);
    this.assign('diqu', diqu);
    if (diqu) {
      map.diqu = ['like', `%${diqu}%`];
    }
    let sortQuery = this.get('sortQuery');
    if (sortQuery) {
      sortQuery = JSON.parse(sortQuery);
      sortQuery.jiage = -sortQuery.jiage;
      let arrowClass = '';
      if (sortQuery.jiage == -1) {
        arrowClass = 'oi-arrow-bottom';
        o = {jiage: 'DESC'};
      } else {
        arrowClass = 'oi-arrow-top';
        o = {jiage: 'ASC'};
      }
      this.assign('sortQuery', sortQuery);
      this.assign('arrow', arrowClass);
    } else {
      sortQuery = {id: -1, jiage: 1};
      o = {id: 'DESC', jiage: 'ASC'};
      this.assign('sortQuery', sortQuery);
      this.assign('arrow', 'oi-arrow-bottom');
    }
    const mokuaibiaoshi = this.get('mokuaibiaoshi');
    if (mokuaibiaoshi) {
      map.mokuaibiaoshi = mokuaibiaoshi;
    }
    let shangpingleibie = this.get('shangpingleibie') || '[]';
    shangpingleibie = JSON.parse(shangpingleibie);
    this.assign('shangpingleibie', shangpingleibie);
    if (!think.isEmpty(shangpingleibie)) {
      map.shangpingleibie = ['IN', shangpingleibie.map((item) => {
        return selectMap.shangpingleibie[item.substr(0, 1)] + '-' + selectMap.shangpingleibie[item];
      })];
    }
    const groupid = this.get('groupid');
    if (groupid == 12) {
      const faburens = await this.model('member').where({groupid: ['=', groupid]}).getField('id');
      map.faburen = ['IN', faburens];
      map.mokuaibiaoshi = ['IN', [1, 2]];
    }
    const data = await this.model(this.mod.name).where(map).page(this.get('page'), num).order(o).countSelect();
    this.assign('page', this.get('page') || '1');

    delete map.xinxileixing;
    delete map.diqu;
    const tuijianData = await this.model(this.mod.name).where(map).order({id: 'DESC'}).limit(3).select();
    /* 模板赋值并渲染模板 */
    this.assign('childcategory', {
      shangpingleibie: '物料',
      diqu: '地区'
    });
    this.assign('group_id', group_id);
    this.assign('category', cate);
    this.assign('list', data.data);
    this.assign('tuijianData', tuijianData);
    this.assign('totalPages', data.totalPages);
    this.assign('count', data.count);
    this.assign('sort', sort);
    this.assign('nsobj', nsobj);

    this.assign('sortid', sortid);
    // 跨屏
    if (this.isMobile) {
      if (this.isAjax('get')) {
        for (const v of data.data) {
          v.nickname = await get_nickname(v.uid);
          v.create_time = moment(v.create_time).fromNow();
          v.catename = await this.model('category').get_category(v.category_id, 'title');
          v.detail = (v.detail).replace(/<[^>]+>/g, '');
          v.answer_username = await get_nickname(v.answer_users);
          v.update_time = moment(v.update_time).fromNow();
        }

        return this.json(data);
      }
      // console.log(this.mod.name);
      // 手机端模版
      return this.modDisplay('m');
    } else {
      return this.modDisplay();
    }
  }
  /**
   * 信息发布
   * @returns {*}
   */
  async fabuAction() {
    if (this.isPost) {
      const postData = this.post();
      postData.faburen = this.is_login;
      if (!postData.hasOwnProperty('mokuaibiaoshi')) {
        postData.mokuaibiaoshi = 1;
        postData.info_channel = 4;
      } else {
        const map = {
          0: 5,
          1: 4,
          2: 3
        };
        postData.info_channel = map[postData.mokuaibiaoshi];
      }
      const fabuNo = await this.model('cmswing/order').orderid(postData.faburen);
      postData.fabu_no = fabuNo;
      const chuangjianshijian = new Date().toLocaleString();
      postData.chuangjianshijian = chuangjianshijian;
      postData.status = 0;
      postData.create_time = Date.now();
      postData.expired_time = postData.create_time + get_youxiaotianshu(postData.youxiaoqi) * 86400000;
      const id = await this.model('gongxufabu').add(postData);
      if (!id) return this.fail('发布失败');
      return this.success({name: '发布成功！'});
    } else {
      if (this.is_login > 0 && this.user.zhucestatus == 2) {
        const mokuaibiaoshi = this.get('mokuaibiaoshi');
        this.assign('mokuaibiaoshi', mokuaibiaoshi);
        this.active = ['/shangping?mokuaibiaoshi=' + mokuaibiaoshi];
        this.meta_title = getfabutitle(mokuaibiaoshi);
        await this.hook('xinxiUpPics', 'tupian', '', {$hook_key: 'icon'});
        const fengleiRes = await this.model('material').field('id,label,pid').select({where: {status: 1}});
        const fenglei = arr_to_tree(fengleiRes, 0);
        this.assign('fenglei', fenglei);
        return this.modDisplay();
      } else {
        return this.redirect('/');
      }
    }
  }
  /**
   * 详情入口
   * @returns {*}
   */
  async detailAction() {
    // 获取详情id
    const id = this.get('id');
    const error = this.controller('cmswing/error');
    // 判断请求参数是否合法。
    if (!think.isNumberString(id)) {
      return error.noAction('请求参数不合法！');
    }
    // 获取详情信息
    const info = await this.model('question').find(id);
    // 判断信息是否存在
    if (think.isEmpty(info)) {
      return error.noAction('信息不存在！');
    }
    // TODO
    // 访问控制

    // 栏目权限验证
    if (!await this.c_verify('visit', info.category_id)) {
      return error.noAction('您所在的用户组,禁止访问本栏目！');
    }
    this.assign('info', info);

    // seo
    this.meta_title = info.title; // 标题
    this.keywords = info.keyname ? info.keyname : ''; // seo关键词
    this.description = info.description ? info.description : ''; // seo描述

    // 获取面包屑信息
    const breadcrumb = await this.model('cmswing/category').get_parent_category(info.category_id, true);
    this.assign('breadcrumb', breadcrumb);
    // 获取栏目信息
    const cate = await this.category(info.category_id);
    this.assign('category', cate);
    // 当前用户是否关注
    if (this.is_login) {
      const focus = await this.model('question_focus').where({question_id: id, uid: this.user.uid}).find();
      this.assign('focus', focus);
    }
    // 获取当前主题所有关注的用户
    const focususer = await this.model('question_focus').where({question_id: id}).getField('uid');
    this.assign('focususer', focususer);
    // 访问统计
    await this.model('question').where({id: info.id}).increment('view');
    // 话题
    // let topicid = await this.model("keyword_data").where({docid:id,mod_type:1,mod_id:cate.model}).getField("tagid");
    // if(!think.isEmpty(topicid)){
    //     let topic = await this.model("keyword").where({id:["IN",topicid]}).select();
    //     console.log(topic);
    // }
    // 获取回复
    const answer = await this.model('question_answer').where({question_id: id}).select();
    for (const a of answer) {
      a.ccount = await this.model('question_answer_comments').where({answer_id: a.answer_id}).count('id');
    }
    this.assign('answer', answer);
    // console.log(cate);
    // 相关问题
    const where = {docid: id, mod_type: 1, mod_id: cate.model};
    // 获取相关tagid
    const tagid = await this.model('keyword_data').where(where).getField('tagid');
    if (!think.isEmpty(tagid)) {
      // 找出相关的tagid
      const rtid = await this.model('keyword_data').where({tagid: ['IN', tagid], mod_id: cate.model}).getField('docid');
      // 相关问题
      const rq = await this.model('question').where({id: ['IN', rtid]}).limit(10).select();
      this.assign('rq', rq);
    }

    // 不同的设备,压缩不同的图片尺寸
    const str = info.detail;
    if (!think.isEmpty(str)) {
      let img;
      if (this.isMobile) {
        // 手机端
        img = image_view(str, 640, 4);
      } else {
        // pc端

        img = image_view(str, 847, 0);
      }
      info.detail = img;
    }
    await this.hook('homeEdit', 'answer_content', '', {$hook_key: 'answer_content', $hook_type: '2_2_200'});
    if (this.isMobile) {
      if (this.isAjax('get')) {
        for (const v of data.data) {
          v.nickname = await get_nickname(v.uid);
          v.create_time = this.moment(v.create_time).fromNow();
          v.catename = await this.model('cmswing/category').get_category(v.category_id, 'title');
          v.detail = (v.detail).replace(/<[^>]+>/g, '');
          v.answer_username = await get_nickname(v.answer_users);
          v.update_time = moment(v.update_time).fromNow();
        }
        return this.json(data);
      }
      // 手机端模版
      return this.modDisplay('m');
    } else {
      return this.modDisplay();
    }
  }
};
